package ui;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;

public class VadeMecumVideoViewer extends Canvas {

	private byte[] outputVideo;
	private Player player;
	private VideoControl videoControl;
	private Command cmdRepeat;
	private Command cmdContinue;
	private Command cmdBack;
	private Displayable previous;
	protected static int VIEW_OLD_MOVIE = 0;
	protected static int VIEW_NEW_MOVIE = 1;
	
	public VadeMecumVideoViewer(Displayable previous, byte[] outputVideo, int typeOfView) {
		this.outputVideo = outputVideo;
		this.previous    = previous;
		
		if(typeOfView == VIEW_OLD_MOVIE) {
			this.cmdBack 	 = new Command("Voltar", Command.BACK, 0);
			this.cmdRepeat   = new Command("Repetir", Command.SCREEN, 0);
			this.addCommand(this.cmdBack);
		} else {
			this.cmdRepeat   = new Command("Repetir", Command.SCREEN, 0);
			this.cmdContinue = new Command("Prosseguir", Command.OK, 0);
			this.addCommand(this.cmdContinue);
		}
		
		this.addCommand(this.cmdRepeat);
		this.setTitle("Viewing video");
	}
	
	protected void paint(Graphics arg0) {}
	
	public void repeat() {
		try {
			this.player.start();
		} catch (MediaException e) {
			e.printStackTrace();
		}
	}
	
	public void run() {
		InputStream in = new ByteArrayInputStream(this.outputVideo);
		try {
			
			int width  = this.getWidth();
			int height = this.getHeight();
			
			this.player = Manager.createPlayer(in, "video/mp4");
			this.player.realize();
			this.videoControl = (VideoControl) this.player.getControl("VideoControl");
			this.videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);
			this.videoControl.setDisplayLocation(0, 0);
			this.videoControl.setDisplaySize(width, height);
			this.videoControl.setDisplayFullScreen(true);
			this.videoControl.setVisible(true);
			this.player.start();
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (MediaException e) {
			e.printStackTrace();
		}
	}

	public void closeStreams() {
		try {
			this.player.stop();
		} catch (MediaException e) {
			e.printStackTrace();
		}
		this.player.close();
	}
	
	public void commandAction(Command cmd, Displayable arg1) { 
		if(this.cmdRepeat == cmd) {
			this.repeat();
			this.repaint();
		} else if(this.cmdContinue == cmd) {
			this.closeStreams();
		} else if(this.cmdBack == cmd) {
			this.closeStreams();
		}
	}

}
